import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row, Col, Card, Form, Input, Select, Icon, Button, Modal, message, Badge, Tag, DatePicker, InputNumber, Popconfirm
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './Member.less';

const { CheckableTag } = Tag;
const Search = Input.Search;

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible, tagList, checkedTag, checkTag, searchTag, loading } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  const onCancel = () => {
    handleModalVisible(false);
    form.resetFields();
  };

  return (
    <Modal
      title={"添加会员标签"}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={onCancel}
      width={700}
      confirmLoading={loading}
    >
      <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 9 }} label="标签名称">
        <Search
          placeholder="输入标签名称"
          enterButton="搜索"
          size="default"
          onSearch={value => searchTag(value)}
        />
      </FormItem>
      <div className={styles.tagWrapper}>
        {tagList && tagList.map((item, i) => (
          <CheckableTag key={item.labelId} checked={checkedTag ? (item.labelId == checkedTag.labelId) ? true : false : false} className={styles.tag} onChange={(checked) => checkTag(checked, item)}
          >
            {item.labelName}
          </CheckableTag>
        ))
        }
      </div>
    </Modal>
  );
});

@connect(({ member, loading }) => ({
  member,
  loading: loading.models.member,
}))
@Form.create()
export default class Member extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},

    startValue: null,
    endValue: null,

    begPayTime: null,
    endPayTime: null,

    checkedTag: null,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'member/fetchFranList',
      payload: { "pageNum": "0", "pageSize": "0" }
    });

    dispatch({
      type: 'member/fetchMemberList',
      payload: { "pageNum": "1", "pageSize": "10" }
    });

  }

  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;

    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.props.form.getFieldsValue(),
    };

    dispatch({
      type: 'member/fetchMemberList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
      startValue: null,
      endValue: null,
      begPayTime: null,
      endPayTime: null,
    });
    dispatch({
      type: 'member/fetchMemberList',
      payload: { pageNum: 1, pageSize: 10, },
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  _handleSearch() {
    const { dispatch, form } = this.props;
    const params = {
      pageNum: 1,
      pageSize: (this.props.member.memberPagination && this.props.member.memberPagination.pageSize) ? this.props.member.memberPagination.pageSize : 10,
      ...this.props.form.getFieldsValue(),
      begTime: this.state.startValue ? this.state.startValue.format('YYYY-MM-DD HH:mm:mm') : null,
      endTime: this.state.endValue ? this.state.endValue.format('YYYY-MM-DD HH:mm:mm') : null,

      begPayTime: this.state.begPayTime ? this.state.begPayTime.format('YYYY-MM-DD HH:mm:mm') : null,
      endPayTime: this.state.endPayTime ? this.state.endPayTime.format('YYYY-MM-DD HH:mm:mm') : null,
    };

    console.log('paramsparamsparamsparams', params)

    dispatch({
      type: 'member/fetchMemberList',
      payload: params,
    });
  };

  handleModalVisible = flag => {
    if (!flag) {
      this.props.dispatch({
        type: 'member/fetchMemberTag',
        payload: { labelType: 0 }
      });
      this.setState({
        checkedTag: null,
        modalTitle: '添加会员标签',
        modalValue: '',
        modalVisible: !!flag,
      });
    } else {
      this.setState({
        modalVisible: !!flag,
      });
    }
  };

  handleAdd = fields => {
    const { dispatch } = this.props;
    if (this.state.checkedTag && (this.state.selectedRows.length > 0)) {
      let userIdList = [];
      let labelIdList = [];

      for (let i = 0; i < this.state.selectedRows.length; i++) {
        userIdList.push({ userId: this.state.selectedRows[i].userId })
      }

      labelIdList.push({ labelId: this.state.checkedTag.labelId })

      let values = { userIdList: userIdList, labelIdList: labelIdList }

      this.props.dispatch({
        type: 'member/addTag',
        payload: values,
        callback: () => { this.handleModalVisible(false); this._handleSearch() }
      });
    } else {
      message.error('请选择')
    }

  };

  disabledStartDate = (startValue) => {
    const endValue = this.state.endValue;
    if (!startValue || !endValue) {
      return false;
    }
    return startValue.valueOf() > endValue.valueOf();
  }

  disabledEndDate = (endValue) => {
    const startValue = this.state.startValue;
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  }

  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  }

  onStartChange = (value) => {
    this.onChange('startValue', value);
  }

  onEndChange = (value) => {
    this.onChange('endValue', value);
  }


  disabledStartDate1 = (startValue) => {
    const endValue = this.state.endValue;
    if (!startValue || !endValue) {
      return false;
    }
    return startValue.valueOf() > endValue.valueOf();
  }

  disabledEndDate1 = (endValue) => {
    const startValue = this.state.startValue;
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  }

  onStartChange1 = (value) => {
    this.onChange('begPayTime', value);
  }

  onEndChange1 = (value) => {
    this.onChange('endPayTime', value);
  }


  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="手机号">
              {getFieldDecorator('userPhone')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="会员标签">
              {getFieldDecorator('labelName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this._handleSearch()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  _downMember(list) {
    console.log('listlistlistlistlistlistlistlistlistlistlistlistlist', list)
    let recordList = [];
    if (list && list.length > 0) {
      for (let i in list) {
        let one = { userId: list[i].userId }
        recordList.push(one)
      }
    }

    this.props.dispatch({
      type: 'member/downMember',
      payload: { userSts: 1, userList: recordList },
      callback: () => this._handleSearch()
    });
  }

  _upMember(list) {
    let recordList = [];
    if (list && list.length > 0) {

      for (let i in list) {
        let one = { userId: list[i].userId }
        recordList.push(one)
      }
    }

    this.props.dispatch({
      type: 'member/upMember',
      payload: { userSts: 0, userList: recordList },
      callback: () => this._handleSearch()
    });
  }


  renderAdvancedForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="手机号">
              {getFieldDecorator('userPhone')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="会员标签">
              {getFieldDecorator('labelName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="SN码">
              {getFieldDecorator('snCode')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="加盟商">
              {getFieldDecorator('franName', { initialValue: 'undefined' })(
                <Select
                // showSearch
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  {
                    (this.props.member.franList.length > 0) && this.props.member.franList.map(
                      (item, i) => { return <Option key={i} value={item.franName}>{item.franName}</Option> }
                    )
                  }
                </Select>)
              }
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('userSts', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="0">正常</Option>
                  <Option value="1">冻结</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="消费对象">
              {getFieldDecorator('appType', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="1">小萌早教</Option>
                  <Option value="2">小萌绘本</Option>
                  <Option value="3">积分商城</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="注册来源">
              {getFieldDecorator('loginType', { initialValue: null })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="0">家长端</Option>
                  <Option value="1">小萌早教</Option>
                  <Option value="2">小萌绘本</Option>
                  <Option value="3">萌萌乐视频</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="消费金额">
              {getFieldDecorator('minCash')(<InputNumber min={1} />)}
              {'-'}
              {getFieldDecorator('maxCash')(<InputNumber min={1} />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="注册开始时间">
              {getFieldDecorator('begTime')(
                <DatePicker
                  disabledDate={this.disabledStartDate}
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择"
                  onChange={this.onStartChange}
                />
              )}
            </FormItem>
            <FormItem label="注册结束时间">
              {getFieldDecorator('endTime')(
                <DatePicker
                  disabledDate={this.disabledEndDate}
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择"
                  onChange={this.onEndChange}
                />
              )}
            </FormItem>
          </Col>

          <Col md={10} sm={24}>
            <FormItem label="消费开始时间">
              {getFieldDecorator('begPayTime')(
                <DatePicker
                  disabledDate={this.disabledStartDate1}
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择"
                  onChange={this.onStartChange1}
                />
              )}
            </FormItem>
            <FormItem label="消费结束时间">
              {getFieldDecorator('endPayTime')(
                <DatePicker
                  disabledDate={this.disabledEndDate1}
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择"
                  onChange={this.onEndChange1}
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit" onClick={() => this._handleSearch()}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </span>
        </div>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  _checkTag(tag, item) {
    console.log('_checkTag(tag)_checkTag(tag)_checkTag(tag)', tag)
    console.log('_checkTag(tag)_checkTag(tag)_checkTag(item)', item)
    let checked = {}
    checked['labelId'] = item.labelId;
    this.setState({ checkedTag: checked })
  }

  _searchTag(labelName) {
    this.props.dispatch({
      type: 'member/fetchMemberTag',
      payload: { labelType: 0, labelName: labelName }
    });
  }

  render() {
    const tableData = {}
    tableData['list'] = this.props.member.memberList;
    tableData['pagination'] = this.props.member.memberPagination;
    const { selectedRows, modalVisible } = this.state;

    const columns = [
      {
        title: '会员Id',
        dataIndex: 'userId',
        key: 'userId',
      },
      {
        title: '手机号',
        dataIndex: 'userPhone',
        key: 'userPhone',
      },
      {
        title: '会员等级',
        dataIndex: 'userRank',
        key: 'userRank',
        render(val) {
          return <span>{val == '0' ? '普通会员' : val == '1' ? '借阅会员' : 'vip会员'}</span>;
        },
      },
      {
        title: '关联小程序',
        dataIndex: 'isLoginSapp',
        key: 'isLoginSapp ',
        render(val) {
          return <span>{val == '0' ? '否' : val == '1' ? '是' : '其他'}</span>;
        },
      },
      {
        title: '加盟商',
        dataIndex: 'franName',
        key: 'franName',
      },
      {
        title: '状态',
        dataIndex: 'userSts',
        key: 'userSts',
        render(val) {
          return <span style={val == '0' ? { color: '' } : { color: 'red' }}>{val == '0' ? '正常' : val == '1' ? '冻结' : '其他'}</span>;
        },
      },
      {
        title: '积分',
        dataIndex: 'score',
        key: 'score',
      },
      {
        title: '消费金额',
        dataIndex: 'payCash',
        key: 'payCash',
      },
      {
        title: '会员标签',
        dataIndex: 'labelList',
        render(vals) {
          return (
            <Fragment>
              {vals.map(v => {
                const isLongTag = v.labelName.length > 4;
                let tag = '';
                if (isLongTag) {
                  tag = v.labelName.slice(0, 4) + '...'
                } else {
                  tag = v.labelName
                }
                return (
                  <Tag key={v.labelId} color="#108ee9">
                    {tag}
                  </Tag>
                )

              })}
            </Fragment>
          );
        },
      },
      {
        title: '注册时间',
        dataIndex: 'createTime',
        key: 'createTime',
      },
      {
        title: '注册来源',
        dataIndex: 'loginType',
        key: 'loginType',
        render(text) {
          return <span>{text == '0' ? '家长端' : text == '1' ? '小萌早教' : text == '2' ? '小萌绘本' : text == '3' ? '萌萌乐视频' : '其他'}</span>;
        },
      },
      {
        title: '操作',
        key: '操作',
        render: (record) => (
          <Fragment>
            <a onClick={() => this.props.dispatch(routerRedux.push({ pathname: '/member/detail/' + record.userId }))}>查看</a>
          </Fragment>
        ),
      },
    ];

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <PageHeaderLayout title="">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)} disabled={(this.state.selectedRows.length > 0) ? false : true}>
                添加标签
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Popconfirm title="确定要冻结选中的用户吗?" placement="bottom" onConfirm={() => this._downMember(selectedRows)} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="dashed" icon="download">
                      冻结
                  </Button>
                  </Popconfirm>
                  <Popconfirm title="确定要解冻选中的用户吗?" placement="bottom" onConfirm={() => this._upMember(selectedRows)} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="dashed" icon="upload">
                      解冻
                  </Button>
                  </Popconfirm>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={this.props.loading}
              data={tableData}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey="userId"
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} tagList={this.props.member.memberTag} checkedTag={this.state.checkedTag}
          searchTag={(labelName) => this._searchTag(labelName)} checkTag={(tag, item) => this._checkTag(tag, item)} handleAdd={() => this.handleAdd()}
          loading={this.props.loading}
        />
      </PageHeaderLayout>
    );
  }
}
